// pages/orderDetail/orderDetail.js

import utils from '../../utils/util.js';
import {
  PATHS_ALIAS, OTHER_INFO
} from '../../utils/api.js'

import {
  http
} from '../../utils/network.js'

// 倒计时定时器
let timer;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderNo:'',   //订单号
    token:'',       //token
    userId:'',
    mobile:'',
    orderDetail:{},   //订单详情数据
    systemDate:'',    //服务器时间
  },
  onLoad: function(options) {
    this.setData({
      orderNo: options.orderNo ? options.orderNo : '',
      token: wx.getStorageSync('accessToken'),
      mobile: wx.getStorageSync('mobile'),
      userId: wx.getStorageSync('userId'),
    })
    
  },
  onShow: function () {
    this.getOrderDetail();
  },
  onHide: function () {
    clearInterval(timer);
  },
  // 请求订单数据
  getOrderDetail:function(){
    let _this = this;
    let params = {
      mobile: this.data.mobile,	          //手机号	string	必填
      orderNo: this.data.orderNo,	          //订单号	string	必填
      realUserId: wx.getStorageSync('userId'),   //	统一用户userId	string	必填
    };
    http({
      path: PATHS_ALIAS.GET_ORDER_DETAIL,
      params:params,
      success:function(res){
        let orderDetail = res.response.orderDetail;
        orderDetail.bannerUrl = orderDetail.rfdsUrl + orderDetail.activityPicDetail.split(',')[0];
        _this.setData({
          orderDetail,
          systemDate: res.systemDate
        });
        _this.leftTimeRun();
      },
      fail:function(err){
        // //console.log(err);
      }
    })
  },
  // 去支付--1、重新获取token   2、提交订单   3、调用平台组支付接口   4、发起微信支付
  goPay:function(){
    wx.showLoading({
      title: '支付中',
      mask: true
    });
    this.loginThird();
  },
  // 重新获取token及用户信息，防止token失效
  loginThird: function () {
    let _this = this;
    let params = {
      logType: '07',
      thirdId: wx.getStorageSync('unionId'),
      resId: 'weixin',
      userSystem: '0052'
    };

    http({
      path: PATHS_ALIAS.THIRD_USER_LOGIN,
      params: params,
      header: {
        sendChl: 'hzsmk.h5',// 应用渠道(必填) 
        sendClient: 'hellohzsmk', //应用验证码(必填) string 
        clientCode: OTHER_INFO.clientCode
      },
      success: function (res) {
        // //console.log(res);
        wx.setStorageSync('accessToken', res.response.accessToken);
        wx.setStorageSync('userId', res.response.userId);
        wx.setStorageSync('mobile', res.response.mobile);
        _this.setData({
          token: res.response.accessToken,
          mobile: res.response.mobile,
          userId: res.response.userId,
        });
        _this.placeOrder();
      },
      fail: function (err) {
        wx.hideLoading();
        wx.showToast({
          title: '登录失败',
          icon: 'none'
        });
        // //console.log(err);
        if (err.code == 'PY0005') {    //跳转输入手机号登录
          wx.redirectTo({
            url: '/pages/phoneLogin/phoneLogin?fromPage=/pages/my/my',
          })
        }
      },
      complete: function () {

      }
    })
  },
  // 提交订单-二次支付
  placeOrder:function(){
    let _this = this;
    let orderDetail = this.data.orderDetail;
    let params = {
      accessToken: this.data.token,     //	用户令牌	string	必填
      actOrganizes: orderDetail.actOrganizes,     //	活动渠道方	string	必填
      activityId: orderDetail.activityId,     //	活动ID	string	必填
      mobile: this.data.mobile,     //	手机号	string	
      money: orderDetail.entryFee * 10 * 10,     //	报名费金额单位分	string	必填
      orderNo: orderDetail.orderNo,     //	订单号	string	必填
      realUserId: this.data.userId,     //	统一用户userId	string	必填
      theme: orderDetail.theme     //	活动主题	string	必填
    };
    http({
      path: PATHS_ALIAS.SECOND_PAY_ORDER,
      params: params,
      success: function (res) {
        _this.aggPay(res.response.orderInfo);
      },
      fail: function (err) {
        // //console.log(err);
        wx.showToast({
          title: err.msg,
          icon: 'none'
        })
      }
    });
  },
  // 调用平台组统一支付接口
  aggPay: function (orderInfo) {
    let _this = this;
    let orderObj = JSON.parse(utils.base64DecodeUnicode(orderInfo));
    // orderObj.order.thirdAppId = 'wxbb59b4862d99c420';
    //console.log(orderObj);
    let params = {
      openId: wx.getStorageSync('openId'),    //	微信openid，微信公众号支付时必传	string	
      order: orderObj.order,    //		订单信息	object	
      payType: 'WECHAT-SP',    //		支付方式	string	支付宝h5：ALIPAY 微信h5：WECHAT 微信公众号：WECHAT-OA 支付宝app: ALIPAY - APP 微信app：WECHAT-APP，微信小程序：WECHAT-SP
      thirdAppid: OTHER_INFO.appId
    };
    http({
      path: PATHS_ALIAS.AGG_PAY,
      params: params,
      header: {
        accessToken: this.data.token,
        clientCode: OTHER_INFO.clientCode, //测试100001 验证用 300016
        sendChl: 'hzsmk.h5',// 应用渠道(必填) 
        sendClient: 'hellohzsmk', //应用验证码(必填) string  
        sendDev: 'test',//设备号(必填) string  
        serialSeq: new Date().getTime() + this.data.userId, //流水号(必填) string
        userName: this.data.mobile
      },
      success: function (res) {
        //console.log(res);
        let tn = JSON.parse(res.response.tn);
        let paySign = tn.sign;
        //console.log(tn)
        wx.hideLoading();
        // 调用微信支付
        wx.requestPayment({
          'timeStamp': tn.timeStamp + "", //new Date().getTime(),
          'nonceStr': tn.nonce_str, //Math.random().toString(36).substr(2),
          'package': "prepay_id=" + tn.prepay_id, //'prepay_id=*',
          'signType': 'MD5',
          'paySign': paySign,
          'success': function (res) {
            // 支付成功后
            console.log('支付成功:' + JSON.stringify(res));
            _this.confirmGroupOrder('success');
          },
          'fail': function (err) {
            console.log(err);
            // 支付失败，或取消支付.跳转到订单详情
            if (err.errMsg == 'requestPayment:fail cancel') {
              wx.showToast({
                title: '取消支付',
                icon: 'none'
              })
            } else {
              wx.showToast({
                title: '支付失败',
                icon: 'none'
              });
            };
          }
        })
      },
      fail: function (err) {
        // //console.log(err);
        wx.hideLoading();
        wx.showToast({
          title: err.msg,
          icon: 'none'
        });
      }
    })
  },
  // 确认订单--支付成功回调   success-支付成功，fail-支付失败
  confirmGroupOrder: function (orderStatus) {
    let _this = this;
    let orderDetail = this.data.orderDetail;3
    let params = {
      mobile: this.data.mobile,    //	手机号	string	必填
      orderNo: this.data.orderNo,    //		订单号	string	必填
      orderStatus: orderStatus,    //		订单状态	string	必填，，success-支付成功，fail-支付失败
      realUserId: this.data.userId,    //		统一用户userId	string	必填
    };
    http({
      path: PATHS_ALIAS.CONFIRM_GROUP_ORDER,
      params: params,
      success: function (res) {
        //console.log(res)
        let groupId = res.response.groupId;
        // 参团者支付成功跳转到拼团详情
        if (groupId != 0 && orderDetail.groupLeader == 'N'){
          wx.navigateTo({
            url: `/pages/groupBuy/groupBuy?groupId=${res.response.groupId}`,
          });
        }else{
          _this.getOrderDetail();
        } 
      },
      fail: function (err) {
        //console.log(err);
        // wx.navigateTo({
        //   url: `/pages/groupBuy/groupBuy?groupId=${res.response.groupId}`,
        // });
        _this.getOrderDetail();
      }
    })

  },
  // 拨打电话
  telPhone(e) {
    //console.log(e);
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.id,
    })
  },
  // 支付倒计时
  leftTimeRun: function () {
    let _this = this;
    

    _this.leftTimeRunFilter();
    timer = setInterval(function () {
      let timeLeft = _this.leftTimeRunFilter();
      if (timeLeft<0){
        clearInterval(timer);
      }
    }, 1000)
  },
  // 参团倒计时--计算时间
  leftTimeRunFilter: function () {
    let orderDetail = this.data.orderDetail;
    let systemDate = this.data.systemDate;
    // 支付剩余时间  服务器时间+10分钟 - 下单时间
    let timeLeft =
      10 * 60 * 1000 +this.timeToTimestamp(orderDetail.tradeTime) - this.timeToTimestamp(systemDate);
    if (!orderDetail.timeLeft && orderDetail.timeLeft!='0'){
      orderDetail.timeLeft = timeLeft;
    };
    if (orderDetail.timeLeft > 0) {
      orderDetail.timeLeft = orderDetail.timeLeft - 1000;
    }
    this.setData({
      orderDetail: orderDetail
    });
    return orderDetail.timeLeft;
  },



  // 日期时间转时间戳   2018-12-02 17:09:09
  timeToTimestamp: function (time) {
    var date = new Date(time.replace(/-/g, "/"));
    var time1 = date.getTime();
    return time1;
  },
})